package com.daxia.bumall.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;

import com.daxia.bumall.common.Logs;

public class FileUtils {
    public static String normalizePath(String path) {
        if (StringUtils.isBlank(path)) {
            return path;
        }
        path = normalizeFilePath(path);
        return (path.endsWith("/") ? path : path + "/");
    }
    
    public static String normalizeFilePath(String path) {
        if (StringUtils.isBlank(path)) {
            return path;
        }
        path = path.replace("\\", "/").replace("\\", "/").replace("//", "/").replace("//", "/");
        return path;
    }
    
    public static boolean isExitFile(String fileUrl) {
    	File file = new File(fileUrl);
    	return file.exists();
    }
    
    /**
     * Return if the file is an image
     * @param file
     * @return
     */
    public static boolean isImagefile(String file) {
        String extension = FilenameUtils.getExtension(file).toLowerCase();
        return (extension.equals("jpg") || extension.equals("jpeg") || extension.equals("bmp")
                || extension.equals("gif") || extension.equals("png"));
    }
    
    /**
     * 批量删除图片
     * */
	public static void deleteFile(String fileNames) {
		String[] list = fileNames.split(",");
		for(int i = 0; i < list.length; i++) {
			String filePath = "D:/nanche_image/" + list[i];
			File file = new File(filePath);
			if(file.exists()) {
				file.delete();
			}else {
				Logs.COMMON.debug("图片不存在...");
			}
		}
	}
	
	public static void downloadImg(String urlString, String filename,String savePath) throws Exception {  
        // 构造URL  
        URL url = new URL(urlString);  
        // 打开连接  
        URLConnection con = url.openConnection();  
        //设置请求超时为5s  
        con.setConnectTimeout(5*1000);  
        // 输入流  
        InputStream is = con.getInputStream();  
      
        // 1K的数据缓冲  
        byte[] bs = new byte[1024];  
        // 读取到的数据长度  
        int len;  
        // 输出的文件流  
       File sf=new File(savePath);  
       if(!sf.exists()){  
           sf.mkdirs();  
       }  
       OutputStream os = new FileOutputStream(sf.getPath()+"/"+filename);  
        // 开始读取  
        while ((len = is.read(bs)) != -1) {  
          os.write(bs, 0, len);  
        }  
        // 完毕，关闭所有链接  
        os.close();  
        is.close();  
    }   
}
